<template>
  <view class="search-page">
    <!-- 状态栏占位 -->
    <!-- <view class="status-bar"></view> -->
    
    <!-- 页面标题栏 -->
    <view class="title-header">
      <view class="back-btn" @click="goBack">
        <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
      </view>
      <text class="page-title">搜索商品</text>
      <view class="placeholder"></view>
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-container">
        <view class="search-input-wrapper">
          <image class="search-icon" src="/static/Images/search/search-icon.png" mode="aspectFit"></image>
          <input 
            class="search-input" 
            type="text" 
            placeholder="请输入商品名" 
            v-model="searchText"
            @input="onSearchInput"
            @confirm="onConfirm"
            focus
          />
        </view>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>
    
    <!-- 历史记录 -->
    <view class="history-section" v-if="!hasSearched">
      <view class="history-header">
        <text class="history-title">历史记录</text>
        <image class="delete-icon" src="/static/Images/search/delete-icon.svg" mode="aspectFit" @click="clearHistory"></image>
      </view>
      
      <view class="history-tags">
        <view 
          class="history-tag" 
          v-for="(item, index) in historyList" 
          :key="index"
          @click="selectHistory(item)"
        >
          <text class="tag-text">{{ item }}</text>
        </view>
      </view>
    </view>

    <!-- 搜索结果列表 -->
    <view class="result-section" v-else>
      <scroll-view class="result-scroll" scroll-y="true" @scrolltolower="onScrollToLower" :style="{ height: scrollHeight }">
        <view class="result-container">
          <view 
            class="result-item"
            v-for="(goods, index) in goodsList"
            :key="goods.id || index"
            @click="onGoodsClick(goods)"
          >
            <image class="result-img" :src="safeImgUrl(goods.imgs?.[0])" mode="aspectFill" />
            <view class="result-info">
              <text class="result-title">{{ goods.goods_name || goods.title }}</text>
              <text class="result-price">¥{{ goods.price }}</text>
            </view>
          </view>

          <view v-if="loading" class="loading">加载中...</view>
          <view v-if="!loading && goodsList.length === 0" class="empty">暂无数据</view>
          <view v-if="!hasMore && goodsList.length > 0" class="no-more">没有更多数据</view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { getStorage, setStorage, removeStorage } from '@/utils/storage'
export default {
  data() {
    return {
      searchText: '',
      historyList: [],
      // 结果与分页
      goodsList: [],
      page: 1,
      size: 10,
      hasMore: true,
      loading: false,
      hasSearched: false,
      scrollHeight: 'calc(100vh - 184px)' // 44px状态栏 + 44px标题栏 + 48px搜索栏 + 48px边距
    }
  },
  methods: {
    onSearchInput(e) {
      this.searchText = e.detail.value
    },
    onConfirm() {
      this.performSearch(this.searchText)
    },
    
    goBack() {
      uni.navigateBack({
        url:'/pages/index/index'
      })
    },
    
    selectHistory(item) {
      this.searchText = item
      this.performSearch(item)
    },
    
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空历史记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.historyList = []
            // 同步清除本地缓存
            removeStorage('search_history')
          }
        }
      })
    },
    
    async performSearch(keyword) {
      const kwd = (keyword || '').trim()
      if (!kwd) {
        uni.showToast({ title: '请输入关键词', icon: 'none' })
        return
      }
      // 添加到历史记录并持久化
      if (!this.historyList.includes(kwd)) {
        this.historyList.unshift(kwd)
        if (this.historyList.length > 10) this.historyList = this.historyList.slice(0, 10)
        setStorage('search_history', this.historyList)
      } else {
        // 如已存在则移动到最前并持久化（优化手感）
        const idx = this.historyList.indexOf(kwd)
        if (idx > 0) {
          this.historyList.splice(idx, 1)
          this.historyList.unshift(kwd)
        }
        setStorage('search_history', this.historyList)
      }
      // 重置分页并开始拉取
      this.page = 1
      this.hasMore = true
      this.goodsList = []
      this.hasSearched = true
      await this.fetchList()
    },

    async fetchList() {
      if (this.loading || !this.hasMore) return
      this.loading = true
      try {
        // 与商品列表页搜索一致：class_id:0, type:0, kwd, page, size
        let res
        const params = { class_id: 0, type: 0, kwd: this.searchText, page: this.page, size: this.size }
        if (this.$api?.goods?.getGoodsList) {
          res = await this.$api.goods.getGoodsList(params)
        } else {
          const { goodsApi } = await import('@/utils/api')
          res = await goodsApi.getGoodsList(params)
        }
        const list = Array.isArray(res?.data) ? res.data : []
        this.goodsList = this.goodsList.concat(list)
        if (!list.length || list.length < this.size) {
          this.hasMore = false
        } else {
          this.page += 1
        }
      } catch (e) {
        console.error('搜索请求失败:', e)
        uni.showToast({ title: e.message || '搜索失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    onScrollToLower() {
      this.fetchList()
    },

    onGoodsClick(goods) {
      const id = goods?.id || goods?.goods_id
      if (!id) {
        uni.showToast({ title: '未获取到商品ID', icon: 'none' })
        return
      }
      uni.navigateTo({ url: `/pages/goods/goodsdetail?id=${encodeURIComponent(id)}` })
    },

    safeImgUrl(url) {
      if (!url) return ''
      return String(url).trim().replace(/`/g, '')
    }
  },
  
  onLoad(options) {
    // 读取本地缓存的历史记录
    const cached = getStorage('search_history', [])
    if (Array.isArray(cached)) this.historyList = cached

    const kw = options?.kwd || ''
    if (kw) {
      this.searchText = kw
      // 首屏直达结果
      this.performSearch(kw)
    }
  }
}
</script>

<style scoped>
.search-page {
  background-color: #ffffff;
  min-height: 100vh;
}

.status-bar {
  height: 44px;
  background-color: #ffffff;
}

.title-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: transparent;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  text-align: center;
}

.placeholder {
  width: 60rpx;
  height: 60rpx;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.search-container {
  flex: 1;
  margin-right: 12px;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 38.4rpx;
  padding: 8px 12px;
  height: 51.2rpx;
}

.search-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  opacity: 0.6;
}

.search-input {
  flex: 1;
  font-size: 14px;
  color: #333333;
  background-color: transparent;
  border: none;
  outline: none;
}

.search-input::placeholder {
  color: #999999;
}

.cancel-btn {
  font-size: 16px;
  color: #333333;
  padding: 8px 0;
}

.history-section {
  padding: 16px;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.delete-icon {
  width: 20px;
  height: 20px;
  opacity: 0.6;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  background-color: #f0f0f0;
  border-radius: 16px;
  padding: 6px 12px;
  display: inline-flex;
  align-items: center;
}

.tag-text {
  font-size: 14px;
  color: #666666;
}

/* 适配不同屏幕 */
@media screen and (max-width: 375px) {
  .title-header {
    padding: 0 24rpx;
    height: 80rpx;
  }
  
  .page-title {
    font-size: 32rpx;
  }
  
  .back-btn {
    width: 56rpx;
    height: 56rpx;
  }
  
  .back-icon {
    width: 36rpx;
    height: 36rpx;
  }
  
  .placeholder {
    width: 56rpx;
    height: 56rpx;
  }
  
  .search-header {
    padding: 8px 12px;
  }
  
  .history-section {
    padding: 12px;
  }
}
.result-section {
  background: #fff;
}
.result-scroll {
  height: 100%;
}
.result-container {
  padding: 12px 16px 20px;
}
.result-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}
.result-img {
  width: 80px;
  height: 80px;
  background: #f5f5f5;
  border-radius: 8px;
}
.result-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.result-title {
  font-size: 14px;
  color: #333;
}
.result-price {
  font-size: 16px;
  color: #ff4757;
  font-weight: 600;
}
.loading, .empty, .no-more {
  text-align: center;
  color: #999;
  font-size: 12px;
  padding: 12px 0;
}
</style>